<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2018/8/8
 * Time: 14:28
 */
namespace PddWechat\Models\User\Service;

use Dai\Framework\Base\BaseService;
use Dai\Framework\Base\BaseSessionInfo;
use Dai\Framework\Library\CacheClass;
use Dai\Framework\Library\Log;
use PddWechat\Models\Pddorder\Data\PddOrderData;
use PddWechat\Models\User\Data\UserData;
use PddWechat\Models\User\Param\DirectMemberListParam;

class DirectMemberList extends BaseService
{
    public function __construct()
    {
        $this->userdata = new UserData();
        $this->pddOrder = new PddOrderData();
    }

    public function execute($basePageInfo)
    {
        /** @var BaseSessionInfo $sessionData */
        $sessionData = $basePageInfo->sessionInfo;
        $openid = $sessionData->openId;
        /** @var DirectMemberListParam $params*/
        $params = $basePageInfo->params;
        $memberList = $this->getDirectMemberList($openid,$params->pn,$params->rn);
        return $memberList;
    }

    private function getDirectMemberList($openid,$pn,$rn)
    {
        $memberList = $this->userdata->getMemberListAsPageListByOpenId($openid,$pn,$rn);
        if(!empty($memberList)) {
            $openIds = [];
            foreach ($memberList as $item) {
                if(!empty($item->openId)) {
                    array_push($openIds, $item->openId);
                }
            }
            if(!empty($openIds)) {
                $res = $this->userdata->getDirectMemsIndirectMemsNumByOpenIds($openIds);
                foreach ($memberList as $item) {
                    if(!empty($res)) {
                        foreach ($res as $it) {
                            if($item->openId == $it['inviteOpenId']) {
                                $item->directMemberNum = intval($it['cnt']) + 1;
                                break;
                            }else {
                                $item->directMemberNum = 1;
                            }
                        }
                    }else {
                        $item->directMemberNum = 1;
                    }
                    $id = $item->id;
                    $tag = "UserId" . $id;
                    $offerMoney = CacheClass::cacheDataByRedis(__METHOD__,$tag,function () use ($id){
                        return $this->pddOrder->selectDirectUserIncome($id);
                    });
                    $item->offerMoney = floatval($offerMoney/100);
                }
            }
        }
        return $memberList;
    }
}